<template>
  <div class="template-manage">
    <div class="template-manage-title">新建/编辑模板</div>
    <section v-loading="loading" class="template-manage-main">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" class="form">
        <el-form-item label="名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板内容" required>
          <div class="selectbtn" @click="addContent">添加</div>
          <el-card v-if="imagesList.length" class="news-image">
            <ul>
              <li
                v-for="(item, index) in imagesList"
                :key="index"
              >
                <el-row :gutter="10">
                  <el-col :span="20">
                    <el-input v-model="item.name" placeholder="请输入名称" @blur="isEmpty" />
                    <el-radio-group v-model="item.type" @change="handleChange(item,index)">
                      <el-radio :label="0">图片</el-radio>
                      <el-radio :label="1">文本</el-radio>
                      <el-radio :label="2">颜色</el-radio>
                    </el-radio-group>
                    <template v-if="item.type === 0">
                      <div>
                        <img
                          v-if="item.content"
                          class="upload-img"
                          title="点击重新上传"
                          :src="item.contentOos"
                          @click="handleFileUpload('image',index)"
                        >
                        <div v-else class="image-upload-content">
                          <div class="icon-wrap" @click="handleFileUpload('image',index)">
                            <i class="el-icon-plus avatar-uploader-icon" />
                          </div>
                        </div>

                      </div>

                    </template>
                    <template v-else-if="item.type === 1">
                      <el-input
                        v-model="item.content"
                        placeholder="请输入内容"
                        type="textarea"
                        :autosize="{ minRows: 3, maxRows: 6}"
                        style="width: 100%"
                      />
                    </template>
                    <div v-else class="select-color">
                      <el-color-picker v-model="item.content" />
                    </div>
                  </el-col>
                  <el-col :span="4">
                    <el-button
                      style="padding: 3px 0; font-size: 20px;"
                      type="text"
                      icon="el-icon-delete"
                      @click="imagesDel(item, index)"
                    />
                  </el-col>
                </el-row>
              </li>
            </ul>
          </el-card>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="form.sort" placeholder="请输入排序号（值越大，越靠前）" />
        </el-form-item>
      </el-form>
    </section>
    <section class="template-manage-footer">
      <el-button style="padding: 10px 30px;" @click="() =>{$router.back()}">取 消</el-button>
      <el-button type="primary" @click=" submit('form')">确 定</el-button>
    </section>
    <image-no-cropper-upload
      v-if="uploadFile.showUpload===2"
      ref="imageUpload"
      :accept="uploadFile.accept"
      :limit="1"
      :show-chunks="true"
      :multiple="false"
      :chunk-size="uploadFile.chunksize"
      @close="uploadFile.showUpload = -1"
      @success="uploadSuccess"
      :isOss='isOss'
    >
      <div slot="tip" class="upload-tip">
        <i class="el-icon-info" />
        :
        {{ uploadFile.fileType | filterTip }}
      </div>
    </image-no-cropper-upload>

  </div>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog'
import ImageNoCropperUpload from '@/components/ImageNoCropperUpload' // base on element-ui
import { insertTemplatePool, updatetTemplatePool, getTemplatePool } from '../api/index.js'

export default {
  name: 'TemplateManage',
  components: { ImageNoCropperUpload },
  directives: { elDragDialog },
  filters: {
    filterTip(ft) {
      if (ft === 'image') {
        return '只能上传：图片文件'
      } else if (ft === 'video') {
        return '只能上传：视频文件'
      } else {
        return '请上传附件'
      }
    }
  },
  data() {
    return {
      loading: false,
      isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false,
      form: {
        id: '',
        templateName: '',
        sort: '',
        templateBaseType: '',
        templateContent: ''
      },
      rules: {
        templateName: [
          { required: true, message: '请输入模板名称', trigger: 'blur' },
          { min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
        ],
        templateBaseType: [
          { required: true, message: '请选择模板库类型', trigger: 'change' }
        ]
      },
      imagesList: [],
      state: 'create',
      uploadFile: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        showUpload: -1, // 1视频 2图片 3附件
        accept: '',
        fileType: '',
        fileIndex: 0
      },
      contentAdd: {
        name: '',
        type: 0,
        content: '',// 上传图片
        contentOos:""
      }
    }
  },
  created() {
    this.state = this.$route.query.type === 'u' ? 'update' : 'create'
    if (this.$route.query.type === 'u' || this.$route.query.type === 'copy') {
      if (!this.$route.query.i) {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
      } else {
        this.getData(this.$route.query.i)
      }
    } else {
      this.form.templateBaseType = this.$route.query.templateBaseType
    }
  },
  methods: {
    isEmpty(e) {
      if (e.target.value === '') {
        this.$message({
          message: '名称不能为空！',
          type: 'warning'
        })
      }
    },
    handleFileUpload(fileType, i) {
      this.uploadFile.fileType = fileType
      this.uploadFile.fileIndex = i
      if (fileType === 'video') {
        this.uploadFile.accept = 'video/mp4'
        this.uploadFile.showUpload = 1
      } else if (fileType === 'image') {
        this.uploadFile.accept = 'image/*'
        this.uploadFile.showUpload = 2
      } else {
        this.uploadFile.accept = ''
        this.uploadFile.showUpload = 3
      }
    },
    /**
     * 添加内容
     */
    addContent() {
      const obj = Object.assign({}, this.contentAdd)
      this.imagesList.push(obj)
    },

    /**
     * 内容-删除
     */
    imagesDel(item, index) {
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.imagesList.splice(index, 1)
      }).catch()
    },

    /**
     * 上传图片成功
     * */
    uploadSuccess(id, files) {

          console.log(id,"___ct");
          console.log(files,")))");
      if (id) {
        const fileType = this.uploadFile.fileType
        const fileIndex = this.uploadFile.fileIndex
        if (fileType === 'image') {
          this.imagesList[fileIndex].content = id
          if (files[0].ossPath) {
          this.imagesList[fileIndex].contentOos = files[0].ossPath
          }
        }
      }
      this.uploadFile.showUpload = -1
    },

    submit() {
      if (this.imagesList.length === 0) {
        this.$message({
          message: '请添加模板内容！',
          type: 'warning'
        })
        return
      }

      if (this.imagesList.some(item => item.name === '')) {
        this.$message({
          message: '请填写内容名称！',
          type: 'warning'
        })
        return
      }

      if (this.imagesList.some(item => !item.content)) {
        this.$message({
          message: '请上传或填写内容',
          type: 'warning'
        })
        return
      }
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            params['templateContent'] = this.imagesList.length > 0 ? JSON.stringify(this.imagesList) : ''
            return new Promise((resolve, reject) => {
              insertTemplatePool(params).then(() => {
                this.dialogVisible = false
                loading.close()
                this.$message({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
                this.$router.back()
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })

            const params = Object.assign({}, this.form)

            params['templateContent'] = this.imagesList.length > 0 ? JSON.stringify(this.imagesList) : ''
            return new Promise((resolve, reject) => {
              updatetTemplatePool(params).then(() => {
                this.dialogVisible = false
                loading.close()
                this.$message({
                  title: '成功',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                })
                this.$router.back()
              }).catch(error => {
                reject(error)
                loading.close()
              })
            })
          } else {
            return false
          }
        })
      }
    },
    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getTemplatePool({ id: id }).then(res => {
          loading.close()
          const data = res.data.data
          for (const key in this.form) {
            this.form[key] = data[key]
          }
          this.form.templateContent = this.form.templateContent && JSON.parse(this.form.templateContent)
          this.imagesList = data.templateContent && JSON.parse(data.templateContent) || []
          if (this.$route.query.type === 'copy') {
            this.form.id = ''
          }
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    handleChange(item, index) {
      item.content = ''
      item.contentOos = ''
      if (this.imagesList[index].content !== '') this.imagesList[index].content = ''
       if (this.imagesList[index].contentOos !== '') this.imagesList[index].contentOos = ''
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">

.template-manage {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .template-manage-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;

    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .template-manage-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;

    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }

    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }

    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }

    &:hover {
      overflow: auto;
    }

    .form {
      width: 1000px !important;
      margin: 0 auto;

      .el-select {
        width: 100%;
      }

      .line {
        text-align: center;
      }
    }

    .select-data {
      display: inline-block;
      background: rgba(246, 246, 246, 1);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
      margin-right: 5px;
      margin-bottom: 8px;

      i {
        cursor: pointer;
        padding-left: 5px;
      }
    }

    .selectbtn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      @include border-color(1px, dotted, $mainColor);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      @include font-color($mainColor);
      text-align: center;
      cursor: pointer;
      margin-bottom: 10px;
    }

    .news-image {
      .el-card__header {
        padding-top: 8px;
        padding-bottom: 8px;
      }

      ul {
        list-style: none;

        li {
          border-bottom: dashed 1px #e5e5e5;
          position: relative;
          padding-bottom: 10px;
          margin-bottom: 10px;
        }
      }

      .upload-img {
        width: 300px;
        height: 160px;
        display: block;
        cursor: pointer;
      }

      .image-upload-content {
        .icon-wrap {
          width: 300px;
          height: 160px;
          display: flex;
          align-items: center;
          justify-content: center;
          background: rgba(247, 247, 248, 1);
          border: 1px solid rgba(226, 227, 232, 1);
          border-radius: 4px;

          .avatar-uploader-icon {
            font-size: 48px;
            color: #dadada;
            width: 300px;
            text-align: center;
          }
        }

        img {
          display: block;
          width: 300px;
          height: 160px;
          border-radius: 4px;
        }
      }
    }

    .images-item {
      border-bottom: dashed 1px #e5e5e5;
      position: relative;
      margin-bottom: 10px;

      .upload-img {
        width: 100%;
        height: 160px;
        display: block;
      }

      .el-input {
        display: block;
      }

      .custom-uploader {
        width: 100%;
        display: block;

        .icon-wrap {
          width: 100%;
          height: 160px;
        }
      }

      .el-button {
        position: absolute;
        right: 10px;
        top: 0;
        color: #fff;

        i {
          background: rgba(0, 0, 0, 0.4);
          border-radius: 50%;
          padding: 2px;
        }

        &.image-index-move {
          right: 40px;
        }
      }
    }

    .images-add {
      color: $mainColor;
      font-size: 14px;
      padding-left: 80px;
      cursor: pointer;
      margin-bottom: 20px;
    }

    .upload-img {
      width: 100%;
      height: 160px;
    }

    .attachment-item {
      margin-bottom: 10px;

      .item-btn {
        font-size: 20px;
        cursor: pointer;
      }

      .video-item {
        position: relative;
        cursor: pointer;

        .el-button {
          position: absolute;
          right: 10px;
          top: 0;
          color: #fff;

          i {
            background: rgba(0, 0, 0, 0.4);
            border-radius: 50%;
            padding: 2px;
          }

          &.video-index-move {
            right: 40px;
          }
        }
      }
    }
  }

  .template-manage-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }

  .image-upload-dialog {
    .icon-wrap {
      width: 300px;
      height: 160px;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(247, 247, 248, 1);
      border: 1px solid rgba(226, 227, 232, 1);
      border-radius: 4px;

      .avatar-uploader-icon {
        font-size: 48px;
        color: #dadada;
        width: 300px;
        text-align: center;
      }
    }

    .upload-img {
      display: block;
      width: 300px;
      height: 160px;
      border-radius: 4px;
    }
  }
}
</style>
